<?php

class Debug
{

    static public function get_backtrace()
    {
        $backtrace = array_slice(debug_backtrace(), 1);
        $output = '';
        $output .= 'Stack trace:' . PHP_EOL;

        foreach ($backtrace as $index => $stack)
        {
            // Process args
            $args = array();
            if (!empty($stack['args']))
            {
                foreach ($stack['args'] as $argIndex => $argValue)
                {
                    if (is_object($argValue))
                    {
                        $args[$argIndex] = get_class($argValue);
                    }
                    else
                    if (is_array($argValue))
                    {
                        $args[$argIndex] = 'Array';
                        //substr(print_r($argValue, true), 0, 32);
                    }
                    else
                    if (is_string($argValue))
                    {
                        $args[$argIndex] = "'" . substr($argValue, 0, 32) . (strlen($argValue) > 32 ? '...' : '') . "'";
                    }
                    else
                    {
                        $args[$argIndex] = print_r($argValue, true);
                    }
                }
            }
            // Process message
            $output .= sprintf('#%1$d %2$s(%3$d): %4$s%5$s%6$s(%7$s)', $index, (!empty($stack['file']) ? $stack['file'] : '(unknown file)'), (!empty($stack['line']) ? $stack['line'] : '(unknown line)'), (!empty($stack['class']) ? $stack['class'] : ''), (!empty($stack['type']) ? $stack['type'] : ''), $stack['function'], join(', ', $args)) . PHP_EOL;
        }

        // Throw main in there for the hell of it
        $output .= sprintf('#%1$d {main}', $index + 1);

        return str_replace(ROOT_PATH, '', $output);
    }

}
